﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OneSoft.EntityCore;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Web.Utility;
using BySoft.Server.Common.Enum;
using System.Reflection;
using System.Data;
using BySoft.Server.Business;

namespace BySoft.Web.Site.SysManage
{
    public partial class OperationLogView :  AuthBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitData();
            }
        }

        private List<EntityBase> m_lstEntity
        {
            get
            {
                if (Session["LogView_Entity"] != null)
                {
                    return (List<EntityBase>)Session["LogView_Entity"];
                }
                else
                {
                    return null;
                }
            }
            set
            {
                Session["LogView_Entity"] = value;
            }

        }

        private void InitData()
        {
            string strLogID = Request.QueryString["LogID"];
            if (!string.IsNullOrEmpty(strLogID))
            {
                int nLogID = 0;
                try
                {
                    nLogID = CommonMethod.ConvertToInt(strLogID);

                }
                catch
                {

                }
                if (nLogID != 0)
                {
                    SysUseroperationlogEntity enLog = SysUseroperationlog.GetSysUseroperationlogByID(nLogID);
                    if (enLog != null)
                    {
                        lblUserName.Text = enLog.UserName;
                        lblActionType.Text = BaseEnum.ActionTypeList()[enLog.ActionType].ToString();
                        lblIP.Text = enLog.IPAddress;
                        lblModule.Text = enLog.ModuleName;
                        lblKey.Text = enLog.TheKey;
                        lblTime.Text = ((DateTime)enLog.LogTime).ToString(SystemConfig.DBDateTimeFromat);
                        lblResult.Text = enLog.ActionResult == "1" ? "成功" : "失败";


                        trView.Attributes.CssStyle.Add("OVERFLOW", "auto");
                        List<EntityBase> etyList = DeserializeEntityBase(enLog.DataXML);
                        m_lstEntity = etyList;
                        for (int i = 0; i < etyList.Count; i++)
                        {
                            TreeNode tn = new TreeNode(etyList[i].GetType().Name, i.ToString());
                            TreeNodeCollection nodes = GetTreeNode(etyList[i], tn);
                            foreach (TreeNode subtn in nodes)
                                tn.ChildNodes.Add(subtn);
                            trView.Nodes.Add(tn);
                        }
                        if (trView.Nodes.Count > 0)
                            trView.Nodes[0].Selected = true;

                        BindGridData();

                    }
                }
            }
        }

        protected TreeNodeCollection GetTreeNode(EntityBase ety, TreeNode pNode)
        {
            TreeNodeCollection subNodes = new TreeNodeCollection();
            if (ety.SubEntities != null && ety.SubEntities.Count > 0)
            {
                for (int i = 0; i < ety.SubEntities.Count; i++)
                {
                    EntityBase subety = ety.SubEntities[i];
                    TreeNode tn = new TreeNode(subety.GetType().Name, "#" + pNode.Value + "|" + i);
                    TreeNodeCollection nodeCollection = GetTreeNode(subety, tn);
                    foreach (TreeNode subtn in nodeCollection)
                        tn.ChildNodes.Add(subtn);
                    subNodes.Add(tn);
                }
            }
            if (ety.SubDataSet != null && ety.SubDataSet.Tables.Count > 0)
            {
                foreach (DataTable dt in ety.SubDataSet.Tables)
                {

                    TreeNode tn = new TreeNode(dt.TableName, "%" + pNode.Value + "|" + dt.TableName);
                    for (int x = 0; x < dt.Rows.Count; x++)
                    {
                        TreeNode tnRow = new TreeNode("第" + (x + 1).ToString() + "条", "%" + pNode.Value + "|" + dt.TableName + "|" + x.ToString());
                        tn.ChildNodes.Add(tnRow);
                    }
                    subNodes.Add(tn);
                }
            }
            return subNodes;
        }

        /// <summary>
        /// 反序列化EntityBase
        /// </summary>
        /// <returns></returns>
        protected List<EntityBase> DeserializeEntityBase(string dataxml)
        {
            List<EntityBase> list = new List<EntityBase>();
            string[] spliter = { "\r\n\r\n" };
            string[] etys = dataxml.Split(spliter, StringSplitOptions.RemoveEmptyEntries);
            foreach (string ety in etys)
            {
                if (ety.Length > 0)
                {
                    EntityBase o = SerializeHelper.DeserializeObjectByString(ety, typeof(EntityBase)) as EntityBase;
                    if (o != null)
                        list.Add(o);
                }
            }
            return list;
        }

        private void GetEntityDataForDT(DataTable dt, EntityBase ety)
        {
            if (ety != null)
            {
                PropertyInfo[] propertyInfo = ety.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
                for (int i = 0, j = propertyInfo.Length; i < j; i++)
                {
                    PropertyInfo pi = propertyInfo[i];
                    if (pi.Name == "Key" || pi.Name == "Dirty"
                            || pi.Name == "SubEntities" || pi.Name == "Item" || pi.Name == "SubDataSet"
                            || pi.Name == "TableSchema" || pi.Name == "OringTableSchema"
                            || pi.Name == "DataCollection" || pi.Name == "State" || pi.Name == "Keys"
                            || pi.Name == "Values" || pi.Name == "Count" || pi.Name == "IsReadOnly")
                        continue;
                    DataRow dr = dt.NewRow();
                    dr["Name"] = pi.Name;
                    object objValue = pi.GetValue(ety, null);
                    dr["Value"] = objValue == null ? "" : objValue.ToString();
                    dt.Rows.Add(dr);
                }
            }
        }


        protected DataTable GetSelectedEntityPropertys()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Name", typeof(string)));
            dt.Columns.Add(new DataColumn("Value", typeof(string)));
            List<EntityBase> list = m_lstEntity;
            if (trView.SelectedNode == null
               || list == null)
            {
                return dt;
            }
            string strNodeValue = trView.SelectedNode.Value;
            if (strNodeValue.StartsWith("#"))
            {

                strNodeValue = strNodeValue.Substring(1);
                EntityBase ety = null;
                string[] index = strNodeValue.Split('|');
                for (int i = 0; i < index.Length; i++)
                {
                    int j = int.Parse(index[i]);
                    if (i == 0)
                    {
                        ety = list[j];
                        continue;
                    }

                    if (ety != null)
                        ety = ety.SubEntities[j];

                    GetEntityDataForDT(dt, ety);

                }


            }
            else
            {
                if (strNodeValue.StartsWith("%"))
                {
                    DataTable dtTemp = new DataTable();
                    strNodeValue = strNodeValue.Substring(1);
                    string[] index = strNodeValue.Split('|');
                    if (index.Length == 3)
                    {
                        EntityBase ety = list[CommonMethod.ConvertToInt(index[0])];

                        if (ety != null && ety.SubDataSet != null && ety.SubDataSet.Tables.Count > 0)
                        {

                            dtTemp = ety.SubDataSet.Tables[index[1].ToString()];
                            int nRowIndex = CommonMethod.ConvertToInt(index[2].ToString());
                            DataRow row = dtTemp.Rows[nRowIndex];
                            DataRow nRow;
                            foreach (DataColumn column in dtTemp.Columns)
                            {
                                nRow = dt.NewRow();
                                nRow["Name"] = column.ColumnName;
                                nRow["Value"] = row[column].ToString();
                                dt.Rows.Add(nRow);
                            }
                        }
                    }
                }
                else
                {

                    EntityBase ety = list[CommonMethod.ConvertToInt(strNodeValue)];

                    GetEntityDataForDT(dt, ety);
                }
            }

            return dt;
        }

        protected void trView_SelectedNodeChanged(object sender, EventArgs e)
        {

            BindGridData();
            ScriptManager.RegisterStartupScript(this.up1, this.GetType(), "", "<script>iframeAutoFit();</script>", false);
        }

        private void BindGridData()
        {
            DataTable dt = GetSelectedEntityPropertys();
            if (dt.Rows.Count > 0)
            {

                grdResult.DataSource = dt;
                grdResult.DataBind();

            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, dt);
            }
        }
    }
}
